// 登录表单处理
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const togglePasswordBtn = document.getElementById('togglePassword');
    const loginBtn = document.getElementById('loginBtn');
    const loginText = document.getElementById('loginText');
    const loginSpinner = document.getElementById('loginSpinner');
    const errorMessage = document.getElementById('errorMessage');
    const errorText = document.getElementById('errorText');

    // 密码显示/隐藏切换
    togglePasswordBtn.addEventListener('click', function() {
        const passwordField = passwordInput;
        const icon = this.querySelector('i');
        
        if (passwordField.type === 'password') {
            passwordField.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            passwordField.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
    });

    // 表单验证
    function validateForm() {
        let isValid = true;
        
        // 重置错误提示
        document.getElementById('usernameError').classList.add('hidden');
        document.getElementById('passwordError').classList.add('hidden');
        errorMessage.classList.add('hidden');

        // 验证用户名
        if (!usernameInput.value.trim()) {
            document.getElementById('usernameError').classList.remove('hidden');
            isValid = false;
        }

        // 验证密码
        if (passwordInput.value.length < 6) {
            document.getElementById('passwordError').classList.remove('hidden');
            isValid = false;
        }

        return isValid;
    }

    // 显示错误消息
    function showError(message) {
        errorText.textContent = message;
        errorMessage.classList.remove('hidden');
    }

    // 显示加载状态
    function setLoading(isLoading) {
        if (isLoading) {
            loginBtn.disabled = true;
            loginText.textContent = '登录中...';
            loginSpinner.classList.remove('hidden');
        } else {
            loginBtn.disabled = false;
            loginText.textContent = '登 录';
            loginSpinner.classList.add('hidden');
        }
    }

    // 模拟登录API调用
    async function login(username, password, remember) {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // 模拟验证逻辑
        const mockUsers = [
            { username: 'admin', password: 'admin123', role: 'admin' },
            { username: 'superadmin', password: 'super123', role: 'superadmin' }
        ];

        const user = mockUsers.find(u => u.username === username && u.password === password);
        
        if (user) {
            // 登录成功
            if (remember) {
                localStorage.setItem('rememberedUser', username);
            }
            sessionStorage.setItem('currentUser', JSON.stringify(user));
            return { success: true, user };
        } else {
            // 登录失败
            return { success: false, message: '用户名或密码错误' };
        }
    }

    // 表单提交处理
    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        if (!validateForm()) {
            return;
        }

        const username = usernameInput.value.trim();
        const password = passwordInput.value;
        const remember = document.getElementById('remember').checked;

        setLoading(true);

        try {
            const result = await login(username, password, remember);
            
            if (result.success) {
                // 登录成功，跳转到后台首页
                window.location.href = 'dashboard.html';
            } else {
                showError(result.message);
            }
        } catch (error) {
            showError('登录失败，请稍后重试');
            console.error('Login error:', error);
        } finally {
            setLoading(false);
        }
    });

    // 记住我功能
    const rememberedUser = localStorage.getItem('rememberedUser');
    if (rememberedUser) {
        usernameInput.value = rememberedUser;
        document.getElementById('remember').checked = true;
    }

    // 回车键提交表单
    usernameInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            passwordInput.focus();
        }
    });

    passwordInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            loginForm.dispatchEvent(new Event('submit'));
        }
    });
});

// 防止页面后退到登录页
window.addEventListener('pageshow', function(event) {
    if (event.persisted || window.performance && window.performance.navigation.type === 2) {
        // 检查是否已登录
        if (sessionStorage.getItem('currentUser')) {
            window.location.href = 'dashboard.html';
        }
    }
});
